var express = require('express');
var router = express.Router();

const moment = require('moment')
const AccountModel = require('../../models/AccountModel')

const checkTokenMiddleware = require('../../middlewares/checkTokenMiddleware')

// 获取账单列表
router.get('/account', checkTokenMiddleware, function (req, res, next) {


  AccountModel.find().sort({ time: -1 }).exec((err, data) => {
    if (err) {
      res.json({
        code: '1001',
        msg: '查询失败~~',
        data: null
      })
      return
    }

   res.json({
    code: '0000',
    msg: 'ok',
    data: data
   })
  })
});


router.get('/account/create', checkTokenMiddleware, function (req, res, next) {
  res.render('create', { title: 'Express' });

});

// 添加账单
router.post('/account', checkTokenMiddleware, function (req, res, next) {
  AccountModel.create({
    ...req.body,
    time: moment(req.body.time).toDate()
  }, (err, data) => {
    if (err) {
      res.json({
        code: '1002',
        msg: '插入失败~~',
        data: null
      });
      return
    }
    res.json({
      code: '0000',
      msg: 'ok',
      data: null
    })
  })
});

// 删除账单
router.delete('/account/:id', checkTokenMiddleware, function (req, res, next) {
  AccountModel.deleteOne({ _id: req.params.id }, (err, data) => {
    if (err) {
      res.json({
        code: '1003',
        msg: '删除失败~~',
        data: null
      })
      return
    }
    res.json({
      code: '0000',
      msg: '删除成功',
      data: null
    });
  })
});

// 获取单个账单
router.get('/account/:id', checkTokenMiddleware, function (req, res, next) {
  AccountModel.findById(req.params.id, (err, data) => {
    if (err) {
      res.json({
        code: '1004',
        msg: '查询失败~~',
        data: null
      })
      return
    }
    res.json({
      code: '0000',
      msg: 'ok',
      data: data
    })
  })
});

// 更新账单
router.patch('/account/:id', checkTokenMiddleware, function (req, res, next) {
  AccountModel.findByIdAndUpdate(req.params.id, req.body, (err, data) => {
    if (err) {
      res.json({
        code: '1005',
        msg: '更新失败~~',
        data: null
      })
      return
    }
    res.json({
      code: '0000',
      msg: '更新成功',
      data: null
    })
  })
});

module.exports = router;
